<template>
  <div class="box">
    <h1>{{title}}</h1>
    <div class="usericon">
      <img :src="usericon" @click="openicon" alt="选择头像" title="选择头像">
      <router-link to="/mobile">
        手机验证码登录
        <span class="fa fa-mobile"></span>
      </router-link>
      <router-link to="/email">
        邮箱验证码登录
        <span class="fa fa-envelope-o"></span>
      </router-link>
    </div>

    <!-- 头像列表 -->
    <ul class="icon_box" v-show="usericonseen">
      <li v-for="(item,index) of iconarr" :key="index">
        <img :src="item.src" alt="头像" @click="icon_item(item.src)">
      </li>
    </ul>
    <el-form
      :model="ruleForm2"
      status-icon
      :rules="rules2"
      ref="ruleForm2"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm2.username" placeholder="请输入您的用户名"></el-input>
      </el-form-item>
      <el-form-item label="用户密码" prop="pass">
        <el-input type="password" v-model="ruleForm2.pass" autocomplete="off" placeholder="请输入您的密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
          type="password"
          v-model="ruleForm2.checkPass"
          autocomplete="off"
          placeholder="再次输入密码"
        ></el-input>
      </el-form-item>

      <el-form-item label="角色" prop="role">
        <el-select v-model="role" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item>
        <span class="login">已有账号？
          <router-link to="/login">登录</router-link>
        </span>
      </el-form-item>-->
      <el-form-item prop="captcha" class="captcha_box">
        <div v-html="svghtml.img" @click="getSvg" class="svg_box" title="点击更换验证码"></div>
        <el-input v-model="ruleForm2.captcha" placeholder="请输入图片验证码"></el-input>
      </el-form-item>
      <el-form-item class="login_box">
        <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
        <el-button @click="resetForm('ruleForm2')">重置</el-button>
        <span class="login">已有账号？
          <router-link to="/login">登录</router-link>
        </span>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import moment from "moment"
import axios from "axios";
import Router from "vue-router";
export default {
  mounted () {
    this.icons();
    this.getSvg();
  },
  data () {
    var userName = (rule, value, callback) => {
      //用户名正则，4到16位（字母，数字，下划线，减号）
      // var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
      // console.log(uPattern.test(value))
      var value = value.toString().trim();
      if (value == "") {
        return callback(new Error("用户名不能为空"));
      } else if (value == "郭占铎" || value == "老铁") {
        return callback(new Error("输入有误！"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value == "" || value.length < 6) {
        callback(new Error("密码不安全"));
      } else {
        if (this.ruleForm2.checkPass !== "") {
          this.$refs.ruleForm2.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm2.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var checkCaptcha = (rule, value, callback) => {
      console.log(value);
      if (this.svghtml.text != value.toLowerCase()) {
        callback(new Error("图片验证码错误"));
      } else {
        callback();
      }
    };
    return {
      // 默认的头像
      usericon: "../../static/images/portraiticon/0.jpg",
      title: "注册页面",
      svghtml: "",
      ruleForm2: {
        pass: "",
        checkPass: "",
        username: "",
        captcha: ""
      },
      rules2: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        username: [{ validator: userName, trigger: "blur" }],
        captcha: [{ validator: checkCaptcha, trigger: "blur" }]
      },
      //头像列表显示
      usericonseen: false,
      iconarr: [],
      roleList: [{
        value: 'admin',
        label: '管理员'
      }, {
        value: 'network',
        label: '网络部'
      }, {
        value: 'consult',
        label: '咨询'
      }],
      // 角色
      role: 'network'
    };
  },
  methods: {
    success (msg) {
      this.$message({
        message: msg,
        type: "success"
      });
    },
    fault (msg) {
      this.$message.error(msg);
    },
    // 头像
    icons () {
      for (var i = 1; i < 98; i++) {
        this.iconarr.push({
          src: "../../static/images/portraiticon/" + i + ".jpg"
        });
      }
    },
    // 显示头像列表
    openicon () {
      this.usericonseen = !this.usericonseen;
    },
    // 头像点击关闭列表
    icon_item (data) {
      this.usericon = data;
      this.usericonseen = !this.usericonseen;
    },
    // 注册用户
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          var that = this;
          // 询问是否选择头像
          if (that.usericon == "../../static/images/portraiticon/0.jpg") {
            this.fault("请选择头像");
            return;
          } else {
            axios.post('api/register', {
              username: this.ruleForm2.username,
              password: this.ruleForm2.pass,
              usericon: this.usericon,
              role: this.role,
              time: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
            })
              .then(res => {
                if (res.data.status == 0) {
                  that.success(res.data.msg);
                  // 登陆后跳转
                  this.$router.push({ path: "/login" });
                } else if (res.data.status == 1) {
                  that.fault(res.data.msg);
                }

              }).catch(error => {
                console.log(error)
              })
          }
        }
      });
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    getSvg () {
      axios.get('api/captcha').then(res => {
        this.svghtml = res.data;
      }).catch(error => {
        console.log(error)
      })
    }
  }
};
</script>
<style lang="stylus" scoped>
.box {
  min-width: 320px;
  max-width: 440px;
  max-height: 600px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  background: #f0f0f0;
  border-radius: 10px;

  h1 {
    font-size: 24px;
    color: #333;
    text-align: center;
    padding: 15px;
  }

  .usericon {
    overflow: hidden;
    display: flex;
    justify-content: space-evenly;
    margin: 10px 0;

    a {
      line-height: 50px;
      font-size: 14px;

      span {
        font-size: 18px;
        line-height: 50px;
        color: #409EFF;
      }

      .fa-envelope-o {
        font-size: 16px;
      }
    }

    img {
      border-radius: 50%;
      width: 50px;
      height: 50px;
      background: #fff;
      text-align: center;
    }
  }

  .icon_box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    background: #fff;
    justify-content: center;
    position: absolute;
    top: 0;
    left: 0;
    min-height: 200px;
    max-height: 400px;
    overflow: auto;
    border: 1px solid #adadad;
    z-index: 1;

    li {
      width: 36px;
      height: 36px;
      margin: 3px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .login {
    margin-left: 10px;
    font-size: 14px;

    a {
      color: #409EFF;
    }
  }

  .el-form {
    padding-right: 40px;
  }
}
</style>
